package com.tiyende.kash.loop.utils

import android.os.Handler
import android.os.Looper
import com.tiyende.kash.loop.utils.log.TiyendeLogger
import java.util.concurrent.atomic.AtomicBoolean

/**
 * 定时器工具类
 * @property period 执行间隔时间，默认1000毫秒
 */
class TiyendeTimerThread(private var period: Long = 1000L) {
    private val handler = Handler(Looper.getMainLooper())
    private val isRunning = AtomicBoolean(false)

    private var listener: ITimingThreadListener? = null
    private var runnable: Runnable? = null

    /**
     * 设置定时器监听器
     */
    fun setTimingListener(listener: ITimingThreadListener) {
        this.listener = listener
    }

    /**
     * 设置线程的执行间隔时间
     * @param delayMillis 间隔时间（毫秒）
     */
    fun setThreadDelayMillis(delayMillis: Long) {
        if (delayMillis > 0) {
            period = delayMillis
        }
    }

    /**
     * 启动定时器
     */
    fun startThread() {
        if (isRunning.getAndSet(true)) {
            TiyendeLogger.e("The current task is already running")
            return
        }

        TiyendeLogger.e("Task Started")
        runnable = createRunnable()
        runnable?.let { handler.postDelayed(it, period) }
    }

    /**
     * 停止定时器
     */
    fun stopThread() {
        if (!isRunning.getAndSet(false)) {
            return
        }

        TiyendeLogger.e("Task Stopped")
        runnable?.let { handler.removeCallbacks(it) }
        runnable = null
        listener?.onStopped()
    }

    /**
     * 暂停定时器
     */
    fun pauseThread() {
        if (!isRunning.getAndSet(false)) {
            return
        }

        TiyendeLogger.e("Task Paused")
        runnable?.let { handler.removeCallbacks(it) }
        listener?.onPaused()
    }

    /**
     * 恢复定时器
     */
    fun resumeThread() {
        if (isRunning.getAndSet(true)) {
            TiyendeLogger.e("Task is already running")
            return
        }

        TiyendeLogger.e("Task Resumed")
        runnable = createRunnable()
        runnable?.let { handler.postDelayed(it, period) }
    }

    /**
     * 重启定时器
     */
    fun restartThread() {
        stopThread()
        startThread()
    }

    /**
     * 检查定时器是否正在运行
     */
    fun isRunning(): Boolean = isRunning.get()

    /**
     * 获取当前间隔时间
     */
    fun getPeriod(): Long = period

    /**
     * 创建定时任务 Runnable
     */
    private fun createRunnable(): Runnable {
        return Runnable {
            if (!isRunning.get()) {
                return@Runnable
            }

            try {
                listener?.onLoading()
            } catch (e: Exception) {
                TiyendeLogger.e("Error in onLoading callback: ${e.message}")
                stopThread()
                return@Runnable
            }

            runnable?.let { handler.postDelayed(it, period) }
        }
    }

    /**
     * 清理资源
     */
    fun release() {
        stopThread()
        listener = null
    }

    /**
     * 定时器监听接口
     */
    interface ITimingThreadListener {
        /**
         * 定时回调
         */
        fun onLoading()

        /**
         * 定时器停止回调（可选）
         */
        fun onStopped() {}

        /**
         * 定时器暂停回调（可选）
         */
        fun onPaused() {}
    }
}